package proj.pt.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import proj.pt.model.Course;
import proj.pt.model.Exam;
import proj.pt.model.SubCourse;
import proj.pt.model.Subject;
import proj.pt.model.User;

public class ExamController extends CustomSimpleFormController {

	protected Object formBackingObject(HttpServletRequest request)
    throws Exception{
		
		// getting the id from the request, if it is supplied as parameter.
		// else -1 will be set.
		long id = ServletRequestUtils.getLongParameter(request, "id", -1);
		
		// if id value is greater than -1, then requesting to lead an already existing from database,
		// else create a new object.
		Exam exam = null;
		if(id > -1){
			// load from database
			exam = getLogicProcessor().getExam(new Long(id));
		} //end if
		
		// there may be chance that false id has given for loading from database, and that is not present there, so  will be null;
		if(exam == null)
		return new Exam();
		else return exam;
	}
	
	protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
		Map dataMap = super.referenceData(request, command, errors);
		
		Exam exam = (Exam)command;
		
		String action = WebUtils.getAction(request);
		
		if("action_course_select".equals(action)){
			// course selected, so load batches and semesters according to that.
			dataMap.put("batches", getLogicProcessor().getCourseBatches(exam.getCourse()));
			dataMap.put("semesters", getLogicProcessor().getSubCourses(exam.getCourse()));
			
		} else if(exam.getSubCourse() != null){
			// semester already available as selected, so reain the batches and semester list
			// as per this selection.
			if(exam.getSubCourse().getCourse() != null)
			exam.setCourse(getLogicProcessor().getCourse(exam.getSubCourse().getCourse().getId()));
			
			dataMap.put("batches", getLogicProcessor().getCourseBatches(exam.getSubCourse().getCourse()));
			dataMap.put("semesters", getLogicProcessor().getSubCourses(exam.getSubCourse().getCourse()));
			
		} //end else if
		
		
		dataMap.put("examTypes", getLogicProcessor().getExamTypes());
		dataMap.put("subjects", getLogicProcessor().getSubjectBySemester(exam.getSubCourse()));
		
		User currentUser = (User)dataMap.get("currentUser");
		dataMap.put("courses", getLogicProcessor().getCourses(currentUser));
		
		return dataMap;
	} //end referenceData
	
	
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(SubCourse.class, "subCourse", new SubCourseEditor(getLogicProcessor()));
		binder.registerCustomEditor(Course.class, "course", new CourseEditor(getLogicProcessor()));
		binder.registerCustomEditor(Subject.class, "subject", new SubjectEditor(getLogicProcessor()));
		binder.registerCustomEditor(Date.class, "examDate", new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));
	}
	
	
	/**
	 * This method does the validation.
	 */
	protected void onBindAndValidate(HttpServletRequest request,
            Object command,
            BindException errors) throws Exception {
		
		// if no validation required, then just return from this method.
		if(!doValidate(request))return;
		
				
		Exam exam = (Exam)command;
		
		if(!StringUtils.hasLength(exam.getName())){
			errors.reject("examName.required", "Exam Name required.");
		} //end if
		
		
		// look for exam Id 
		if(!StringUtils.hasLength(exam.getExamId())){
			errors.reject("examId.required", "Exam ID required.");
		} else {
			// look for exam id already exist or not.
			if(!getLogicProcessor().validateExamId(exam)){
				errors.reject("examId.exist", "Exam Id exists, please enter a unique Id.");
			} //end if
		}
		
		if(!StringUtils.hasLength(exam.getBatchYear())){
			errors.reject("batch.required", "Batch required.");
		} //end if
		
		if(exam.getSubCourse() == null){
			errors.reject("semester.required", "Semester required.");
		} //end if
		
		if(exam.getSubject() == null){
			errors.reject("subject.required", "Subject required.");
		} //end if
		
		if(exam.getExamDate() == null){
			errors.reject("examDate.required", "Exam date required.");
		} //end if
		
		if(exam.getTotalMark() == null){
			errors.reject("totalMark.required", "Total mark required.");
		} //end if
		
		if(exam.getPassMark() == null){
			errors.reject("passMark.required", "Pass mark required.");
		} //end if
		
		if(exam.getTotalMark() != null && exam.getPassMark() != null &&
				exam.getPassMark() > exam.getTotalMark()){
			errors.reject("passMark.notcorrect", "Pass mark is not valid, it cannot be more than Total mark.");
		}
		
		if(!StringUtils.hasLength(exam.getExamType())){
			errors.reject("examType.required", "Exam Type required.");
		} //end if
	}
	
		
	protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors)
     throws Exception {
		
		String action = WebUtils.getAction(request);
		
		if("action_save".equals(action)){
			getLogicProcessor().saveOrUpdateExams((Exam)command);
		} else if("action_delete".equals(action)){
			getLogicProcessor().deleteExams((Exam)command);
		} else if("action_cancel".equals(action)){
			// do nothing
		} else{
			// do nothing.
		} 
				
		ModelAndView  mav = new ModelAndView();
		mav.setView(new RedirectView(getSuccessURI()));
		return mav;
	} //end onSubmit
	
	
}
